package cn.wk.libs4a.view.phonecontact;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import cn.wk.libs4a.WKBaseActivity;

/**
 * 联系人相关工具类
 */
public class WKPhoneContactUtils {

	/**
	 * 是否显示头像，没头像能快不少
	 */
	public static boolean showAvatar = false;

	private ContentResolver resolver; // 联系人解析
	private WKBaseActivity act;// 上下文

	public WKPhoneContactUtils(WKBaseActivity act) {
		this.act = act;
		resolver = act.getContentResolver();
	}

	/**
	 * 获取联系人缓存
	 */
	public List<WKPhoneContactBean> getContactsCache() {
		long t = System.currentTimeMillis();
		List<WKPhoneContactBean> contacts = act.app().db
				.findAll(WKPhoneContactBean.class);
		System.out.println("lazy cost1 =" + (System.currentTimeMillis() - t));
		return contacts;
	}

	/**
	 * 查询通讯录联系人姓名
	 */
	public List<WKPhoneContactBean> getContacts() {
		List<WKPhoneContactBean> contacts = new ArrayList<WKPhoneContactBean>();
		try {
			ContentResolver resolver = act.getContentResolver();
			// 定义一个List来封装系统联系人的信息
			Cursor cursor = resolver.query(
					ContactsContract.Contacts.CONTENT_URI, null, null, null,
					null);
			while (cursor.moveToNext()) {
				// 获取联系人ID
				int id = cursor.getInt(cursor
						.getColumnIndex(ContactsContract.Contacts._ID));
				// 获取联系人姓名
				String name = cursor
						.getString(cursor
								.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

				Cursor phones = resolver.query(
						ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
						null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID
								+ " = " + id, null, null);
				String pStr = "";
				while (phones.moveToNext()) {
					String phoneNumber = phones
							.getString(phones
									.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
					pStr += phoneNumber;
					pStr += ",";
				}
				phones.close();

				WKPhoneContactBean bean = new WKPhoneContactBean(id, name, pStr);
				// bean.initAvatar(getContactPhone(id));
				Bitmap b = getContactPhone(id);
				bean.setHasAvatar(b != null);
				if (b != null) {
					String key = "mobile_contact_avatar_" + id;
					bean.setImgKey(key);
					act.app().imageLoader.loader.getMemoryCache().put(key, b);

					String str = getContactPhoneStr(id);
					act.app().imageLoader.loader.saveBitmap(b, key);
					// act.app().imageLoader.loader.getDiscCache().put(key,
					// arg1);
				}
				contacts.add(bean);
			}
			cursor.close();
			// 对集合进行排序
			if (contacts != null && contacts.size() > 0) {
				Collections.sort(contacts,
						new Comparator<WKPhoneContactBean>() {
							public int compare(WKPhoneContactBean lhs,
									WKPhoneContactBean rhs) {
								try {
									return (WKPhoneContactUtils.getPingYin(lhs
											.getName()).toUpperCase())
											.compareTo(WKPhoneContactUtils
													.getPingYin(rhs.getName())
													.toUpperCase());
								} catch (Exception e) {
									return 0;
								}
							}
						});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 更新缓存
		for (int i = 0; i < contacts.size(); i++) {
			act.app().db.save(contacts.get(i));
		}

		return contacts;
	}

	/**
	 * 获取联系人图片Uri
	 */
	private String getContactPhoneUri(long contactId) {
		try {
			Uri uri = ContentUris.withAppendedId(
					ContactsContract.Contacts.CONTENT_URI, contactId);
			return uri.toString();
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 获取联系人图片
	 * 
	 * @param contactId
	 * @return
	 */
	private Bitmap getContactPhone(long contactId) {
		try {
			if (showAvatar == false)
				return null;
			Uri uri = ContentUris.withAppendedId(
					ContactsContract.Contacts.CONTENT_URI, contactId);
			InputStream input = ContactsContract.Contacts
					.openContactPhotoInputStream(resolver, uri);
			Bitmap photo = BitmapFactory.decodeStream(input);
			return photo;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 获取联系人图片
	 * 
	 * @param contactId
	 * @return
	 */
	private String getContactPhoneStr(long contactId) {
		Uri uri = ContentUris.withAppendedId(
				ContactsContract.Contacts.CONTENT_URI, contactId);
		InputStream input = ContactsContract.Contacts
				.openContactPhotoInputStream(resolver, uri);
		Bitmap photo = BitmapFactory.decodeStream(input);

		photo = photo == null ? null : photo;
		// return photo;
		return uri.toString();
	}

	/**
	 * 将字符串中的中文转化为拼音,其他字符不变
	 * 
	 * @param inputString
	 * @return
	 */
	public static String getPingYin(String inputString) {
		HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
		format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		format.setVCharType(HanyuPinyinVCharType.WITH_V);

		char[] input = inputString.trim().toCharArray();
		String output = "";

		try {
			for (int i = 0; i < input.length; i++) {
				if (java.lang.Character.toString(input[i]).matches(
						"[\\u4E00-\\u9FA5]+")) {
					String[] temp = PinyinHelper.toHanyuPinyinStringArray(
							input[i], format);
					output += temp[0];
				} else
					output += java.lang.Character.toString(input[i]);
			}
		} catch (BadHanyuPinyinOutputFormatCombination e) {
			e.printStackTrace();
		}
		return output;
	}

	/**
	 * 获取汉字串拼音首字母，英文字符不变
	 * 
	 * @param chinese
	 *            汉字串
	 * @return 汉语拼音首字母
	 */
	public static String getFirstSpell(String chinese) {
		StringBuffer pybf = new StringBuffer();
		char[] arr = chinese.toCharArray();
		HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
		defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		for (int i = 0; i < arr.length; i++) {
			if (arr[i] > 128) {
				try {
					String[] temp = PinyinHelper.toHanyuPinyinStringArray(
							arr[i], defaultFormat);
					if (temp != null) {
						pybf.append(temp[0].charAt(0));
					}
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					e.printStackTrace();
				}
			} else {
				pybf.append(arr[i]);
			}
		}
		return pybf.toString().replaceAll("\\W", "").trim();
	}

	/**
	 * 获取汉字串拼音，英文字符不变
	 * 
	 * @param chinese
	 *            汉字串
	 * @return 汉语拼音
	 */
	public static String getFullSpell(String chinese) {
		StringBuffer pybf = new StringBuffer();
		char[] arr = chinese.toCharArray();
		HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
		defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		for (int i = 0; i < arr.length; i++) {
			if (arr[i] > 128) {
				try {
					pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i],
							defaultFormat)[0]);
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					e.printStackTrace();
				}
			} else {
				pybf.append(arr[i]);
			}
		}
		return pybf.toString();
	}
}